//
//  PurchaseDetailViewController.m
//  YYPHSpeedJump
//
//  Created by speedjump on 16/1/29.
//  Copyright © 2016年 sujiang. All rights reserved.
//

#import "PurchaseDetailViewController.h"
#import "PurchaseDetailTableViewCell.h"
#import "PurchaseCommentTableViewCell.h"
#import "RelevantTableViewCell.h"
#import "RelevantCollectionViewCell.h"
#import "BigImageViewController.h"
@interface PurchaseDetailViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSInteger page;
    UIView *baseView;
    CommentView *commentView;
}
@end

@implementation PurchaseDetailViewController
- (NSMutableArray*)reasonArr
{
    if (!_reasonArr) {
        _reasonArr = [NSMutableArray array];
        
    }
    return _reasonArr;
    
}
- (NSMutableArray*)commentArr
{
    if (!_commentArr) {
        _commentArr = [NSMutableArray array];
        }
    return _commentArr;
}
- (NSMutableArray *)relevantArr
{
    if (!_relevantArr) {
        _relevantArr = [NSMutableArray array];
    }
    return _relevantArr;
}
- (NSMutableArray *)hostArr
{
    if (!_hostArr) {
        _hostArr = [NSMutableArray array];
    }
    return _hostArr;
}
- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title =@"心愿详情";
    
    self.tabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth,kScreenHeight+20)];
     self.tabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tabelView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRereshing)];
    self.tabelView.delegate = self;
    self.tabelView.dataSource = self;
    [self.view addSubview:self.tabelView];
   
    page =1;
    [self requestData];
    [self requestRelvantData];
     [self addSubViews];
}
- (void)headerRereshing
{
    page = 1;
    [self requestData];
}
- (void)footerRefresh
{
    page++;
    [self requestData];
}
- (void)requestData
{
    if (self.purchaseModel !=nil) {
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kBaseUrl,kWishCommentUrl];
    NSDictionary *dict = @{@"page":[NSNumber numberWithInteger:page],@"wish_id":self.purchaseModel.wish_id};
    [NetworkHandle getUpDataWithUrl:urlStr class:NSClassFromString(@"SDCommentModel") dictionary:dict firstKey:@"data" secondKey:@"list" success:^(NSArray *array)
     {
         if (page == 1) {
             [self.commentArr removeAllObjects];
         }
         [self.commentArr addObjectsFromArray:array];
         if (self.commentArr.count >= 10 && self.tabelView.footer == nil&&self.segment.selectedSegmentIndex ==1) {
             self.tabelView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
         }
         [self.tabelView.header  endRefreshing];
         [self.tabelView.footer endRefreshing];
              }
     ];
     [NetworkHandle getInfoWithUrl:urlStr dictionary:dict success:^(NSDictionary *dictionary) {
         self.wishdic = dictionary[@"data"];
     }];
    }
    [self.tabelView reloadData];

}
- (void)requestRelvantData
{ if (self.purchaseModel !=nil) {
    NSString *relevantUrl = [NSString stringWithFormat:@"%@%@",kBaseUrl,kRelevantUrl];
    NSDictionary *relevantDic = @{@"wish_id":self.purchaseModel.wish_id};
    [NetworkHandle getUpDataWithUrl:relevantUrl class:NSClassFromString(@"PurchaseModel") dictionary:relevantDic firstKey:@"data" secondKey:@"relate_wishes" success:^(NSArray *array)
     {
         [self.relevantArr addObjectsFromArray:array];
     }
     ];
    [NetworkHandle getUpDataWithUrl:relevantUrl class:NSClassFromString(@"PurchaseModel") dictionary:relevantDic firstKey:@"data" secondKey:@"hotest_wishes" success:^(NSArray *array)
     {
         [self.hostArr addObjectsFromArray:array];
     }
     ];
}
}
- (void)setModel:(PurchaseModel *)model
{
    self.purchaseModel = model;
}
- (void)addSubViews
{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth,111)];
    [self.tabelView setTableHeaderView:headerView];
    UILabel * goodName = [[UILabel alloc]initWithFrame:CGRectMake(13, 15, 200, 14)];
    goodName.font =[UIFont systemFontOfSize:14];
    goodName.text = [NSString stringWithFormat:@"商品名:%@",self.purchaseModel.wish_commodity_name];
    [headerView addSubview:goodName];
    UILabel * goodPrice = [[UILabel alloc]initWithFrame:CGRectMake(13, 42, 200, 14)];
    goodPrice.font = [UIFont systemFontOfSize:14];
    goodPrice.text =  [NSString stringWithFormat:@"商品价格:%@",self.purchaseModel.original_price];
    [headerView addSubview:goodPrice];
    self.xyProgressView = [[XYProgressView alloc]initWithFrame:CGRectMake(kScreenWidth-80, 14, 46, 46)];
    self.xyProgressView.arcUnfinishColor = kColors(221, 124, 17, 1);
    self.xyProgressView.arcFinishColor =kColors(221, 124, 17, 1);
   
    if ([self.purchaseModel.up_num integerValue]<100) {
         self.xyProgressView.percent =[self.purchaseModel.up_num floatValue]/100;
         self.xyProgressView.percentLabel = [NSString stringWithFormat:@"%@%%",self.purchaseModel.up_num];
    }
    if ([self.purchaseModel.up_num integerValue]==100) {
       
        self.xyProgressView.percent =1;
        self.xyProgressView.percentLabel = @"完成";
    }

    [headerView addSubview:self.xyProgressView];
    self.segment = [[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObjects:@"详情",@"评论",@"相关",nil]];
    self.segment.frame = CGRectMake(16, 70, kScreenWidth-32, 30);
    [headerView addSubview:self.segment];
    self.segment.tintColor = kColors(218, 166, 46, 1);
    
    
    [self.segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    self.segment.selectedSegmentIndex = 0;
    self.addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
   self.addBtn.frame = CGRectMake(kScreenWidth-70, kScreenHeight-70-64, 50, 50);
    [self.addBtn setBackgroundColor:kColors(218, 166, 46, 1)];
    [self.addBtn setTitle:@"添加" forState:UIControlStateNormal];
    self.addBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    self.addBtn.layer.cornerRadius = 25;
    [self.addBtn addTarget:self action:@selector(addBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.addBtn];
    self.addBtn.hidden =YES;
    self.shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.shareBtn.frame = CGRectMake(0, kScreenHeight-44-64, kScreenWidth/2, 44);
    [self.shareBtn setBackgroundColor:kColors(218, 166, 46, 1)];
    [self.shareBtn addTarget:self action:@selector(shareBtnAct:) forControlEvents:UIControlEventTouchUpInside];
    self.shareBtn.hidden = NO;
    [self.shareBtn setTitle:@"分享" forState:UIControlStateNormal];
    
    [self.view addSubview:self.shareBtn];
    self.praiseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.praiseBtn.frame = CGRectMake(kScreenWidth/2, kScreenHeight-44-64, kScreenWidth/2, 44);
    [self.praiseBtn setBackgroundColor:kColors(210, 210, 210, 1)];
    [self.praiseBtn setTitle:@"想要" forState:UIControlStateNormal];
    [self.praiseBtn addTarget:self action:@selector(praiseBtnAct:) forControlEvents:UIControlEventTouchUpInside];
    self.praiseBtn.hidden = NO;
    [self.view addSubview:self.praiseBtn];
}
#pragma mark -----------------点击方法------------------------
//点赞
- (void)praiseBtnAct:(UIButton*)btn
{
        if (![[NSUserDefaults standardUserDefaults] boolForKey:@"logined"]) {
            [Tools showAlert:@"您还未登录,请到个人登录!"];
            return;
        }

    NSString *url = [NSString stringWithFormat:@"%@%@", kBaseUrl, kXYPraiseUrl];
    // NSLog(@"%@",self.model.wish_id);
    NSDictionary *dic = @{@"u":[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"], @"wish_id":self.purchaseModel.wish_id};
    //if ([self.model.uped isEqualToString:@"0"]) {
    
    [NetworkHandle getInfoWithUrl:url dictionary:dic success:^(NSDictionary *dictionary) {
        if ([dictionary[@"code"] isEqualToString:@"200"]) {
            if ([self.purchaseModel.up_num integerValue]<100) {
        
                self.xyProgressView.percent =[self.purchaseModel.up_num floatValue]/100;
                [self.tabelView reloadData];
            }
            if ([self.purchaseModel.up_num integerValue]==100) {
                
                self.xyProgressView.percent =1;
                
            }
            [Tools showAlert:@"你的心愿已收到"];
        }
        else{
            [Tools showAlert:dictionary[@"message"]];
        }
        
    }];

}
//分享
- (void)shareBtnAct:(UIButton*)btn
{
    
    NSString *contentText = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"share_word"]];
    [UMSocialData defaultData].extConfig.wechatSessionData.title =@"速降";
    [UMSocialData defaultData].extConfig.wechatTimelineData.title =@"速降";
    [UMSocialData defaultData].extConfig.qqData.title = @"速降";

    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"5699e81567e58e7cba000b92"
                                      shareText:contentText
                                     shareImage:[UIImage imageNamed:@"sujiang"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToWechatSession,UMShareToWechatTimeline,UMShareToQQ,nil]
                                       delegate:nil];

}
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据responseCode得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        // 分享成功返回积分!
        NSString *string = [NSString stringWithFormat:@"%@/user.do?cmd=share_integral", kBaseUrl];
        NSDictionary *dic = @{@"u":[[NSUserDefaults standardUserDefaults]objectForKey:@"user_id"]};
        [NetworkHandle getInfoWithUrl:string dictionary:dic success:^(NSDictionary *dictionary) {
            [Tools showAlert:@"恭喜您获得10分享积分!"];
        }];
        
    }
}

//添加评论
- (void)addBtnAction:(UIButton*)btn
{
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"logined"]) {
        [Tools showAlert:@"您还未登录,请到个人登录!"];
        return;
    }

    baseView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    baseView.backgroundColor = [UIColor grayColor];
    baseView.alpha = 0.5;
    [self.view.window addSubview:baseView];
    commentView = [[CommentView alloc]initWithFrame:CGRectMake(13*kWidthScale, 167*kHeightScale, 349*kWidthScale, 163*kHeightScale)];
    
    [self.view.window addSubview:commentView];
    
    [commentView.returnBtn addTarget:self action:@selector(returnAct:) forControlEvents:UIControlEventTouchUpInside];
    [commentView.commentBtn addTarget:self action:@selector(commentAct:) forControlEvents:UIControlEventTouchUpInside];
}
//返回
- (void)returnAct:(UIButton*)btn
{
    [baseView removeFromSuperview];
    [commentView removeFromSuperview];
}
//提交
- (void)commentAct:(UIButton *)btn
{
        NSString *text = [commentView.commentText.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    [commentView.commentText resignFirstResponder];
    if (text.length < 6) {
        [Tools showAlert:@"输入不能小于6个字符!"];
        return;
    }
    NSString *urlStr = [NSString stringWithFormat:@"%@/user.do?cmd=make_comment_in_wish",kBaseUrl];
    NSDictionary *dic = @{@"comment_content":commentView.commentText.text,@"wish_id":self.purchaseModel.wish_id,@"u":[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"]};
    
    [NetworkHandle getUpDataWithUrl:urlStr class:NSClassFromString(@"SDCommentModel") dictionary:dic firstKey:@"data" secondKey:@"list" success:^(NSArray *array) {
        
        self.commentArr = [NSMutableArray arrayWithArray:array];
        
        [self requestData];
        
        [baseView removeFromSuperview];
        [commentView removeFromSuperview];
    }];
   
   
}
- (void)segmentAction:(id)sender
{
    switch ([sender selectedSegmentIndex]) {
        case 0:
        {
             self.addBtn.hidden =YES;
            self.shareBtn.hidden = NO;
            self.praiseBtn.hidden = NO;
             //self.tabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
            [self.tabelView reloadData];
        }
            break;
        case 1:
        {
            //self.tabelView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;

            self.addBtn.hidden =NO;
            self.shareBtn.hidden = YES;
            self.praiseBtn.hidden = YES;
            [self.tabelView reloadData];
        }
            break;

        case 2:
        {
            //self.tabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
            self.shareBtn.hidden = YES;
            self.praiseBtn.hidden = YES;
            self.addBtn.hidden =YES;
            [self.tabelView reloadData];
            
        }
            break;

            
        default:
            break;
    }
    
}
#pragma mark ----------tabelViewdelegate----------------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.segment.selectedSegmentIndex ==1) {
        return 2;
    }
    return 1;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.segment.selectedSegmentIndex  == 0) {
        return 1;
    }
    if (self.segment.selectedSegmentIndex == 1)
    {
        if (section ==0) {
            return 1;
        }
        return self.commentArr.count;
     
    }
    if (self.segment.selectedSegmentIndex ==2) {
        return 2;
    }
    return 0;

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.segment.selectedSegmentIndex  == 0) {
        PurchaseDetailTableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:@"purchaseDetailCell"];
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"PurchaseDetailTableViewCell" owner:nil options:nil]lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
                         }
        self.imageArr = [self.purchaseModel.img_url componentsSeparatedByString:@";"];
            //心愿商品详情
            cell.reason.text= self.purchaseModel.introduction;

        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.minimumInteritemSpacing = 0;
        layout.minimumLineSpacing =9;
        layout.itemSize = CGSizeMake(250, 250);
        
        [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        
        layout.sectionInset = UIEdgeInsetsMake(9, 9, 9, 9);
        
        self.collectionV = [[UICollectionView alloc] initWithFrame:cell.imageURL.bounds collectionViewLayout:layout];
        self.collectionV.backgroundColor = [UIColor whiteColor];
        self.collectionV.delegate = self;
        self.collectionV.dataSource =self;
        self.collectionV.showsHorizontalScrollIndicator =NO;
        [cell.imageURL addSubview:self.collectionV];
        //注册单元格
        [self.collectionV registerNib:[UINib nibWithNibName:@"RelevantCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"relevantCell"];

        return cell;
    }
    else if (self.segment.selectedSegmentIndex == 1)
    {
        PurchaseCommentTableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"puechaseCommentCell"];
        if (!cell) { 
            cell = [[[NSBundle mainBundle]loadNibNamed:@"PurchaseCommentTableViewCell" owner:nil options:nil]lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
                }
        if (indexPath.section == 0) {
            cell.commentLabel.text =[NSString stringWithFormat:@"%@",self.wishdic[@"wish_reason"]];
            cell.timeLabel.text = self.wishdic[@"wish_create_time"];
            cell.userName.text =self.wishdic[@"nickname"];
            [cell.userImageView sd_setImageWithURL:[NSURL URLWithString:self.wishdic[@"head_img_url"]] placeholderImage:nil ];
        }
        if (indexPath.section == 1) {
            cell.model = self.commentArr[indexPath.row];
        }
     
        return cell;
        }
    else
    {
        RelevantTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"relevantCell"];
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"RelevantTableViewCell" owner:nil options:nil]lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
        }
        if (indexPath.row ==0) {
            cell.titleLable.text = @"更多相关心愿";
            UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
            layout.minimumInteritemSpacing = 0;
            layout.minimumLineSpacing =9;
            layout.itemSize = CGSizeMake((kScreenWidth-45)/3,90);
            
            layout.sectionInset = UIEdgeInsetsMake(5, 9, 3, 9);
            
            self.relevantcollectionV = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 365*kWidthScale, 100) collectionViewLayout:layout];
            self.relevantcollectionV.backgroundColor = [UIColor whiteColor];
            self.relevantcollectionV.delegate = self;
            self.relevantcollectionV.dataSource =self;
            
            //注册单元格
            [self.relevantcollectionV registerNib:[UINib nibWithNibName:@"RelevantCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"relevantCell"];
            

            [cell.baseView addSubview:self.relevantcollectionV];
        }
        if (indexPath.row ==1) {
            cell.titleLable.text = @"热门心愿";
           
            UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
            layout.minimumInteritemSpacing = 0;
            layout.minimumLineSpacing =9;
            layout.itemSize = CGSizeMake((kScreenWidth-45)/3,90);
            
            layout.sectionInset = UIEdgeInsetsMake(5, 9, 3, 9);
            
            self.hostcollectionV= [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 365*kWidthScale, 100) collectionViewLayout:layout];
            self.hostcollectionV.backgroundColor = [UIColor whiteColor];
            self.hostcollectionV.delegate = self;
            self.hostcollectionV.dataSource =self;
            
            //注册单元格
            [self.hostcollectionV registerNib:[UINib nibWithNibName:@"RelevantCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"relevantCell"];
            

            [cell.baseView addSubview:self.hostcollectionV];
        }
       return cell;
    }

   
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.segment.selectedSegmentIndex  == 0) {
        return 525;
    }else if (self.segment.selectedSegmentIndex == 1)
    {
        return 69;
    }else
    {
        return 159;
    }

}

#pragma mark -------collectionViewDelegate--------------
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView == self.collectionV) {
        return self.imageArr.count;
    }
    if (collectionView ==self.relevantcollectionV) {
        return self.relevantArr.count;

    }if (collectionView == self.hostcollectionV) {
        return self.hostArr.count;
    }
    return 0;
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.collectionV) {
        RelevantCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"relevantCell" forIndexPath:indexPath];
        cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
        cell.imageView.layer.cornerRadius =5;
        cell.imageView.layer.borderWidth = 1;
        cell.imageView.layer.borderColor =[UIColor grayColor].CGColor;
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:self.imageArr[indexPath.row]] placeholderImage:nil];
        cell.backgroundColor = [UIColor whiteColor];
        return cell;
    }
    else{
    RelevantCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"relevantCell" forIndexPath:indexPath];
    cell.layer.borderWidth = 1;
    cell.layer.borderColor = [UIColor grayColor].CGColor;
    cell.layer.cornerRadius =5;
    cell.backgroundColor = [UIColor whiteColor];
    if (collectionView == self.relevantcollectionV) {
        cell.purchasemodel = self.relevantArr[indexPath.row];
    }
    if (collectionView == self.hostcollectionV) {
        cell.purchasemodel = self.hostArr[indexPath.row];
    }
    
    return cell;
    }
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.collectionV) {
        BigImageViewController *bigImageV =[[BigImageViewController alloc]init];
        [self.navigationController pushViewController:bigImageV animated:YES];
        bigImageV.imgUrl = self.imageArr[indexPath.row];
       
    }
    else{
    PurchaseDetailViewController *purchaseDetailVC =[[PurchaseDetailViewController alloc]init];
    [self.navigationController pushViewController:purchaseDetailVC animated:YES];
    if (collectionView == self.relevantcollectionV) {
        purchaseDetailVC.purchaseModel = self.relevantArr[indexPath.row];
    }
    
    if (collectionView == self.hostcollectionV) {
        purchaseDetailVC.purchaseModel = self.hostArr[indexPath.row];
    }
    }
    
}
//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
